import * as types from '../mutation-types'

// initial state
// shape: [{ id, quantity }]
const state = {
  cartItems: [],
  sumPrice: 0.00,
  relPrice: 0.00
}

// getters
const getters = {
  cartItems: state => state.cartItems,
  sumPrice: state => state.sumPrice,
  relPrice: state => state.relPrice
}

// actions
const actions = {
  initCartItems: ({commit, state}, cartItems) => commit(types.INIT_CART_ITEMS, {cartItems})
}

// mutations
const mutations = {
  [types.INIT_CART_ITEMS] (state, {cartItems}) {
    state.cartItems = cartItems
    let sumPrice = 0.00
    if (cartItems) {
      for (let item in cartItems) {
        let subPrice = item.quantity * item.price
        sumPrice += subPrice
      }
    }
    state.sumPrice = sumPrice
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
